<template>
  <!-- 查询表单 -->
  <a-collapse v-model:activeKey="activeKey" :bordered="false">
    <a-collapse-panel key="1" :style="customStyle" header="评论管理-查询">
      <a-row>
        <a-col :span="22">
          <a-form ref="queryFormRef" :model="queryFormState">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="评论内容" name="content">
                  <a-input v-model:value="queryFormState.content" placeholder="请输入评论内容" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="更新时间" name="updatedAt">
                  <a-range-picker style="width: 100%" @change="updated" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="评论状态" name="status">
                  <a-select
                    v-model:value="queryFormState.status"
                    :options="statusOptions"
                    placeholder="请选择状态"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="创建时间" name="createdAt">
                  <a-range-picker style="width: 100%" @change="created" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 80px" type="vertical" />
        <a-col :span="1">
          <a-space :size="22" direction="vertical">
            <a-button type="primary" @click="onQuery">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="onReset">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-collapse-panel>
  </a-collapse>
  <!-- 数据表格 -->
  <a-card size="small">
<!--    <a-button size="small" style="margin-bottom: 10px" type="primary" @click="modalVisible = true">-->
<!--      <template #icon>-->
<!--        <PlusOutlined />-->
<!--      </template>-->
<!--      添加-->
<!--    </a-button>-->
    <a-button
      size="small"
      type="primary"
      danger
      :disabled="!hasSelected"
      :loading="rowSelectionState.loading"
      @click="start"
      style="margin-left: 10px"
    >
      <template #icon>
        <DeleteOutlined />
      </template>
      删除
    </a-button>
    <span style="margin-left: 8px">
      <template v-if="hasSelected">
        {{ `选择了 ${rowSelectionState.selectedRowKeys.length} 条数据` }}
      </template>
    </span>
    <!-- 表格 -->
    <a-table
      v-model:pagination="pagination"
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :scroll="{ x: '120%', y: 360 }"
      bordered
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <!-- 是否禁用 -->
        <template v-if="column.dataIndex === 'status'">
          <template v-if="record.status === 1">
            <div class="disabled"></div>
          </template>
          <template v-else>
            <div class="enable"></div>
          </template>
        </template>
        <!-- 操作 -->
        <template v-if="column.dataIndex === 'operations'">
          <div class="action">
<!--            <a-button size="small" type="primary" @click="onEdit(record.id)">-->
<!--              <template #icon>-->
<!--                <EditOutlined />-->
<!--              </template>-->
<!--            </a-button>-->
            <a-popconfirm cancel-text="×" ok-text="√" title="删除？" @confirm="confirm">
              <a-button danger size="small" type="primary" @click="onDelete(record.id)">
                <template #icon>
                  <DeleteOutlined />
                </template>
              </a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <!-- 新增数据模态框 -->
  <a-modal v-model:visible="modalVisible" title="添加评论" @cancel="handleCancel" @ok="handleOk">
    <a-form ref="addFormRef" :model="addFormState" :rules="addFormRules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="评论名" name="content">
            <a-input v-model:value="addFormState.content" placeholder="请输入评论名" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="addFormState.status"
              :options="statusOptions"
              placeholder="请选择是否禁用"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
  <!-- 更新数据抽屉 -->
  <a-drawer
    :body-style="{ paddingBottom: '80px' }"
    :footer-style="{ textAlign: 'right' }"
    :visible="drawerVisible"
    :width="720"
    title="编辑评论信息"
    @close="onClose"
  >
    <a-form ref="updateFormRef" :model="updateFormState" :rules="updateFormRules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="评论内容" name="content">
            <a-input v-model:value="updateFormState.content" placeholder="请输入评论内容" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="updateFormState.status"
              :options="statusOptions"
              placeholder="请选择状态"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onFinish">提交</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
<script lang="ts" setup>
import { computed, reactive, ref, toRefs } from 'vue'
import type { FormInstance, TableColumnType, TableProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { usePagination } from 'vue-request'
import type { Rule } from 'ant-design-vue/lib/form'
import type { IntervalStrDTO, Key } from '@/types/global'
import type { AddComment, Comment, QueryComment, UpdateComment } from '@/types/comment'
import {
  addComment,
  deleteCommentByIds,
  getCommentById,
  queryCommentList,
  updateComment
} from '@/api/comment'

// 下拉列表自定义样式
const customStyle = 'background: #ffffff;' + 'margin-bottom: 10px;' + 'border: none;'

// 状态选择
const statusOptions = computed(() => [
  {
    label: '正常',
    value: 0
  },
  {
    label: '禁用',
    value: 1
  }
])
const queryFormRef = ref<FormInstance>()
const queryFormState = reactive<QueryComment & IntervalStrDTO>({
  content: '',
  status: 0
})
// 查询
const onQuery = () => {
  run({
    ...queryFormState
  })
}
// 重置
const onReset = () => {
  console.log('重置')
  queryFormRef.value?.resetFields()
}

// 选择更新时间间隔
const updated = (date: any, dateString: (string | undefined)[]) => {
  queryFormState.updatedAtStart = dateString[0]
  queryFormState.updatedAtEnd = dateString[1]
}
// 选择创建时间间隔
const created = (date: any, dateString: (string | undefined)[]) => {
  queryFormState.createdAtStart = dateString[0]
  queryFormState.createdAtEnd = dateString[1]
}

// 表格列配置
const columns: TableColumnType<Comment>[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    fixed: 'left',
    align: 'center',
    sorter: true,
    width: 60
  },
  {
    title: '评论内容',
    dataIndex: 'content',
    align: 'center',
    ellipsis: true
  },
  {
    title: '评论人',
    dataIndex: 'nickname',
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    align: 'center',
    sorter: true,
    width: 200
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    align: 'center',
    sorter: true,
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'operations',
    fixed: 'right',
    align: 'center'
  }
]

const activeKey = ref<string[]>(['1'])

// 处理表格变化
const handleTableChange: TableProps['onChange'] = (pagination, filters: any, sorter: any) => {
  run({
    current: pagination.current,
    pageSize: pagination.pageSize,
    sortField: sorter.field,
    sortOrder: sorter.order,
    ...queryFormState
  })
}

const { data, total, run, loading, current, pageSize } = usePagination(queryCommentList, {
  defaultParams: [
    {
      current: 1,
      pageSize: 10
    }
  ],
  pagination: {
    currentKey: 'current',
    pageSizeKey: 'pageSize',
    totalKey: 'data.data.total'
  }
})

// 分页数据
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value
}))
// 评论数据
const dataSource = computed<Comment[]>(() => data.value?.data.data.records || [])

// 新增数据模态框是否可见
const modalVisible = ref<boolean>(false)
const addFormRef = ref<FormInstance>()

// 新增表单
const addFormState = ref<AddComment>({
  content: '',
  status: 0
})
// 新增表单验证规则
const addFormRules: Record<string, Rule[]> = {
  name: [{ required: true, message: '评论名不能为空' }]
}
const handleOk = () => {
  addComment(addFormState.value).then((res) => {
    const { code, msg } = res.data
    message.success(msg)
    if (code == 200) {
      addFormRef.value?.resetFields()
      modalVisible.value = false
      run({
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
        ...queryFormState
      })
    }
  })
}

const handleCancel = () => {
  addFormRef.value?.resetFields()
}
// 抽屉是否可见
const drawerVisible = ref<boolean>(false)
const updateFormRef = ref<FormInstance>()
// 更新表单
const updateFormState = ref<UpdateComment>({
  id: 0,
  content: '',
  status: 0
})

const updateFormRules: Record<string, Rule[]> = {
  name: [{ required: true, message: '评论名不能为空' }]
}

// 编辑
const onEdit = (id: number) => {
  getCommentById(id)
    .then((res) => {
      updateFormState.value = res.data.data
    })
    .catch((error) => {
      console.log(error)
    })
  showDrawer()
}
// 打开抽屉
const showDrawer = () => {
  drawerVisible.value = true
}
// 关闭抽屉
const onClose = () => {
  drawerVisible.value = false
  updateFormRef.value?.resetFields()
}

// 提交编辑
const onFinish = () =>
  updateComment(updateFormState.value).then((res) => {
    const { code, msg } = res.data
    message.success(msg)
    if (code == 200) {
      onClose()
      run({
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
        ...queryFormState
      })
    }
  })
/**
 * ===============================删除==================================
 */
const idList = ref<number[]>([])
// 删除
const onDelete = (id: number) => {
  idList.value = [id]
}
const confirm = () => {
  if (idList.value.length > 0) {
    deleteCommentByIds(idList.value).then((res) => {
      const { code, msg } = res.data
      if (code == 200) {
        message.success(msg)
        run({
          current: pagination.value.current,
          pageSize: pagination.value.pageSize,
          ...queryFormState
        })
      }
    })
  }
}

const rowSelectionState = reactive<{
  selectedRowKeys: Key[]
  loading: boolean
}>({
  selectedRowKeys: [],
  loading: false
})

const hasSelected = computed(() => rowSelectionState.selectedRowKeys.length > 0)
const { selectedRowKeys } = toRefs(rowSelectionState)
const onSelectChange = (selectedRowKeys: Key[]) => {
  rowSelectionState.selectedRowKeys = selectedRowKeys
}
const start = () => {
  rowSelectionState.loading = true
  deleteCommentByIds(rowSelectionState.selectedRowKeys).then((res) => {
    const { code, msg } = res.data
    if (code == 200) {
      rowSelectionState.loading = false
      rowSelectionState.selectedRowKeys = []
      message.success(msg)
      run({
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
        ...queryFormState
      })
    }
  })
}
</script>
<style lang="less" scoped>
.action {
  button:first-child {
    margin-right: 5px;
  }

  button:last-child {
    margin-left: 5px;
  }
}

.disabled,
.enable {
  display: flex;
  justify-content: center;
  font-size: 12px;
}

.disabled::before {
  content: '';
  width: 8px;
  height: 8px;
  background-color: red;
  margin: auto 2px auto 0;
}

.disabled::after {
  content: '禁用';
  margin: auto 2px auto 0;
}

.enable::before {
  content: '';
  width: 8px;
  height: 8px;
  background-color: green;
  margin: auto 2px auto 0;
}

.enable::after {
  content: '启用';
  margin: auto 2px auto 0;
}
</style>